package com.example.hello;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.Nullable;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MyTask2 implements Runnable{
    public  static  final  String TAG="MyTask";
    private Handler handler;

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void run() {
        //获取网络数据
        Log.i(TAG,"run:---");
        //do....延时3s
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        ArrayList<HashMap<String,String>> retList=new ArrayList<HashMap<String,String>>();
        //List<String> retList=new ArrayList<String>();
        try {
            Document doc= Jsoup.connect(" https://www.boc.cn/sourcedb/whpj/").get();
            String title=doc.title();
            Log.i(TAG,"run:title="+title);

            Elements tables=doc.getElementsByTag("table");
            for(Element table:tables) {
                Elements trs = table.getElementsByTag("tr");
                Log.i(TAG, "run:tr.size=" + trs.size());
                if (trs.size() > 1) {
                    for (Element tr : trs) {
                        Elements tds = tr.getElementsByTag("td");
                        Log.i(TAG, "run:td.size=" + tds.size());
                        if (tds.size() > 0) {
                            String td1 = tds.get(0).text();
                            String td2 = tds.get(5).text();
                            Log.i(TAG, "MyTask:" + td1 + "→" + td2);

                            //构造map放入数据
                            HashMap<String,String> map=new HashMap<String,String>();
                            map.put("cname",td1);   //标题文字
                            map.put("cval",td2);//详情描述
                            retList.add(map);
//                            retList.add(td1 + "→" + td2);
                        }
                    }
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回消息给主线程
        //获取MSG对象,收件人：5
        Message msg=handler.obtainMessage(5);
        //内容
        msg.obj=retList;
        handler.sendMessage(msg);
        Log.i(TAG,"sendmsg ok");
    }
}
